package com.ytktt.study.week11.task4;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 基于 ScheduledExecutorService 实现的可过期缓存
 *
 * @author ytk
 */
@Slf4j
public class Cache<String, V> {

    private static final int DEFAULT_CAPACITY = 16;

    private final ConcurrentHashMap<String, V> entryMap;

    private final ScheduledExecutorService scheduledExecutorService;

    private final long expireTime;

    private final TimeUnit unit;

    public Cache(long expireTime, TimeUnit unit) {
        this(DEFAULT_CAPACITY, expireTime, unit);
    }

    public Cache(int initialCapacity, long expireTime, TimeUnit unit) {
        this.entryMap = new ConcurrentHashMap<>(initialCapacity);
        this.expireTime = expireTime;
        this.unit = unit;
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("cache-scheduled-%d").build();
        this.scheduledExecutorService = Executors.newScheduledThreadPool(1, namedThreadFactory);
    }

    public void put(String key, V value) {
        this.entryMap.put(key, value);
        this.scheduledExecutorService.schedule(() -> {
            this.entryMap.remove(key);
            log.info("key: {} expired", key);
        }, this.expireTime, this.unit);
    }

    public void destroy() {
        this.scheduledExecutorService.shutdown();
        this.entryMap.clear();
    }

    public V get(String key) {
        return this.entryMap.get(key);
    }
}
